# Copyright 2020 Huawei Technologies Co., Ltd
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ============================================================================
import numpy as np
import mindspore.nn as nn
from mindspore import Tensor
from mindspore.ops import operations as P


class Net(nn.Cell):
    def __init__(self, config):
        super(Net, self).__init__()
        self.embedding = nn.Embedding(config.n_vocab, config.embedding_size,
                                      False)
        self.lstm = nn.LSTM(config.embedding_size, config.hidden_size,
                            config.num_layers,
                            bidirectional=True)
        # 由于mindspore不支持MaxPool1d，先凑合使用AvgPool1d
        self.maxpool = nn.AvgPool1d(config.pad_size)
        self.fc = nn.Dense(config.hidden_size * 2 + config.embedding_size,
                           config.num_classes)
        self.op = P.Concat(axis=2)
        self.relu = nn.ReLU()
        # 重新排列
        self.transpose = P.Transpose()
        self.squeeze = P.Squeeze()

        # size
        self.shape1 = Tensor(np.ones([2 * config.num_layers, config.batch_size,
                                      config.hidden_size]).astype(np.float32))

    def construct(self, x):
        embed = self.embedding(x)
        out, _ = self.lstm(embed, (self.shape1, self.shape1))
        out = self.op((embed, out))

        out = self.relu(out)
        out = self.transpose(out, (0, 2, 1))
        out = self.maxpool(out)
        out = self.squeeze(out)
        out = self.fc(out)

        return out
